package com.evolved.automata.experimental;

import java.util.LinkedList;

import com.evolved.automata.AITools;
import com.evolved.automata.WeightedValue;

public class SimpleExtinctionPolicy implements BehaviorDistribution.ExtinctionPolicy {
	private double j_PeakWeight=0;
	private double j_StepInterval;
	private double j_ExtinctionRate=1;
	
	public SimpleExtinctionPolicy(double stepInterval, double extinctionRate)
	{
		j_StepInterval=stepInterval;
		j_ExtinctionRate=extinctionRate;
	}
	
	public LinkedList<WeightedValue<Integer>> TransformPoint(LinkedList<WeightedValue<Integer>> baseDistribution)
	{
		// There is a chance of doing nothing, which is based on the extinction rate
		
		
		if (Math.random()<j_ExtinctionRate)
		{
			double originalPeakWeight=0, peakDelta, extinctionDropoff;
			boolean nonZeroPointsP=true;
			LinkedList<WeightedValue<Integer>> newDistrib;
			for (WeightedValue<Integer> action : baseDistribution)
			{
				if (action.GetWeight()>originalPeakWeight)
				{
					originalPeakWeight=action.GetWeight();
				}
			}
			
			if (originalPeakWeight>j_PeakWeight)
			{
				j_PeakWeight=originalPeakWeight;
				return baseDistribution;
			}
			else
			{
				
				peakDelta = j_PeakWeight-originalPeakWeight;
				extinctionDropoff = Math.random()*peakDelta;
				newDistrib = new LinkedList<WeightedValue<Integer>>();
				for (WeightedValue<Integer> action : baseDistribution)
				{
					
					if ((action.GetWeight()-extinctionDropoff)>=j_StepInterval)
					{
						nonZeroPointsP=true;
					}
					newDistrib.add(new WeightedValue<Integer>(action.GetValue(), Math.max(0, AITools.StepFunction(action.GetWeight()-extinctionDropoff, j_StepInterval))));
				}
				if (nonZeroPointsP)
					return newDistrib;
				else
					return null;
			}
		}
		else
			return baseDistribution;
	}
}
